<template>
    <div class="workflow-preview">
        <div class="workflow-preview__header">
            <div class="info">
                <h2>{{ workflow?.name }}</h2>
                <p class="description">{{ workflow?.description }}</p>
                <div class="meta">
                    <el-tag v-for="tag in workflow?.tags" :key="tag" size="small" class="tag">
                        {{ tag }}
                    </el-tag>
                    <span class="category">
                        分类：{{ workflow?.category }}
                    </span>
                </div>
            </div>
            <div class="actions">
                <el-button @click="handleBack">返回列表</el-button>
                <el-button 
                    v-if="canEdit" 
                    type="primary" 
                    @click="handleEdit"
                >
                    编辑工作流
                </el-button>
                <el-button type="primary" @click="handleGenerate" :loading="generating">
                    生成图片
                </el-button>
            </div>
        </div>

        <el-row :gutter="20" class="main-content">
            <!-- 左侧：预览图和参数配置 -->
            <el-col :span="16">
                <el-card class="preview-card">
                    <template #header>
                        <div class="card-header">
                            <span>预览图</span>
                            <el-button-group>
                                <el-button :disabled="!generatedImage" @click="handleDownload">
                                    <el-icon><Download /></el-icon>
                                </el-button>
                                <el-button @click="handleLike">
                                    <el-icon :class="{ active: liked }"><Star /></el-icon>
                                </el-button>
                            </el-button-group>
                        </div>
                    </template>
                    <div class="preview-container" v-loading="generating">
                        <el-image
                            v-if="generatedImage || workflow?.thumbnail"
                            :src="generatedImage || workflow?.thumbnail"
                            fit="contain"
                            :preview-src-list="[generatedImage || workflow?.thumbnail || '']"
                        />
                        <div v-else class="empty-preview">
                            <el-icon><Picture /></el-icon>
                            <span>生成的图片将在这里显示</span>
                        </div>
                    </div>
                </el-card>

                <el-card class="params-card">
                    <template #header>
                        <div class="card-header">
                            <span>参数配置</span>
                            <el-button text @click="resetParams">重置参数</el-button>
                        </div>
                    </template>
                    <el-form
                        ref="paramsFormRef"
                        :model="params"
                        label-width="120px"
                        class="params-form"
                    >
                        <template v-for="param in workflow?.params" :key="param.name">
                            <!-- 文本输入 -->
                            <el-form-item
                                v-if="param.type === 'text'"
                                :label="param.label"
                                :prop="param.name"
                            >
                                <el-input
                                    v-model="params[param.name]"
                                    :placeholder="'请输入' + param.label"
                                />
                            </el-form-item>

                            <!-- 数字输入 -->
                            <el-form-item
                                v-else-if="param.type === 'number'"
                                :label="param.label"
                                :prop="param.name"
                            >
                                <el-input-number
                                    v-model="params[param.name]"
                                    :min="param.min"
                                    :max="param.max"
                                    :step="param.step"
                                />
                            </el-form-item>

                            <!-- 选择器 -->
                            <el-form-item
                                v-else-if="param.type === 'select'"
                                :label="param.label"
                                :prop="param.name"
                            >
                                <el-select
                                    v-model="params[param.name]"
                                    :placeholder="'请选择' + param.label"
                                >
                                    <el-option
                                        v-for="option in param.options"
                                        :key="option.value"
                                        :label="option.label"
                                        :value="option.value"
                                    />
                                </el-select>
                            </el-form-item>

                            <!-- 滑块 -->
                            <el-form-item
                                v-else-if="param.type === 'slider'"
                                :label="param.label"
                                :prop="param.name"
                            >
                                <el-slider
                                    v-model="params[param.name]"
                                    :min="param.min"
                                    :max="param.max"
                                    :step="param.step"
                                />
                            </el-form-item>
                        </template>
                    </el-form>
                </el-card>
            </el-col>

            <!-- 右侧：工作流信息和统计 -->
            <el-col :span="8">
                <el-card class="info-card">
                    <template #header>
                        <div class="card-header">
                            <span>工作流信息</span>
                            <el-tag :type="workflow?.isPublic ? 'success' : 'info'">
                                {{ workflow?.isPublic ? '已发布' : '未发布' }}
                            </el-tag>
                        </div>
                    </template>
                    <el-descriptions :column="1" border>
                        <el-descriptions-item label="作者">
                            {{ workflow?.author }}
                        </el-descriptions-item>
                        <el-descriptions-item label="版本">
                            {{ workflow?.version }}
                        </el-descriptions-item>
                        <el-descriptions-item label="使用次数">
                            {{ workflow?.stats.uses }}
                        </el-descriptions-item>
                        <el-descriptions-item label="点赞数">
                            {{ workflow?.stats.likes }}
                        </el-descriptions-item>
                        <el-descriptions-item label="浏览量">
                            {{ workflow?.stats.views }}
                        </el-descriptions-item>
                    </el-descriptions>
                </el-card>

                <el-card class="history-card">
                    <template #header>
                        <div class="card-header">
                            <span>生成历史</span>
                            <el-button text @click="clearHistory">清空</el-button>
                        </div>
                    </template>
                    <div v-if="generationHistory.length" class="history-list">
                        <div
                            v-for="(item, index) in generationHistory"
                            :key="index"
                            class="history-item"
                            @click="loadHistoryItem(item)"
                        >
                            <el-image :src="item.image" fit="cover" />
                            <div class="history-item-info">
                                <span class="time">{{ formatTime(item.time) }}</span>
                                <el-button
                                    size="small"
                                    @click.stop="downloadHistoryItem(item)"
                                >
                                    下载
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <el-empty v-else description="暂无生成历史" />
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Download, Star, Picture, View, Edit, Delete } from '@element-plus/icons-vue';
import { workflowApi } from '@/api/workflow';
import type { WorkflowTemplate } from '@/types';
import dayjs from 'dayjs';

const props = defineProps<{
    id: string;
}>();

const router = useRouter();
const route = useRoute();
const workflow = ref<WorkflowTemplate>();
const params = ref<Record<string, any>>({});
const generating = ref(false);
const generatedImage = ref('');
const liked = ref(false);
const generationHistory = ref<Array<{ image: string; time: string; params: Record<string, any> }>>([]);
const canEdit = ref(false);

// 获取工作流数据
const fetchWorkflow = async () => {
    try {
        console.log('Fetching workflow:', props.id);
        const response = await workflowApi.getWorkflow(props.id);
        if (!response?.data) {
            throw new Error('工作流不存在');
        }
        workflow.value = response.data;
        console.log('Successfully fetched workflow:', workflow.value.id);
    } catch (error) {
        console.error('Fetch workflow error:', error);
        ElMessage.error('获取工作流失败');
        router.push('/workflow');
    }
};

// 返回列表
const handleBack = () => {
    if (route.query.from === 'edit') {
        router.push('/workflow');
    } else {
        router.back();
    }
};

// 生成图片
const handleGenerate = async () => {
    if (generating.value) return;
    
    try {
        const workflowId = workflow.value?.id;
        if (!workflowId) {
            console.error('Invalid workflow ID for generate operation');
            ElMessage.error('生成失败');
            return;
        }

        generating.value = true;
        console.log('Generating image for workflow:', workflowId);
        const { data } = await workflowApi.executeWorkflow(workflowId, {
            params: params.value
        });
        
        generatedImage.value = data.imageUrl;
        generationHistory.value.unshift({
            image: data.imageUrl,
            time: new Date().toISOString(),
            params: { ...params.value }
        });
        
        ElMessage.success('生成成功');
    } catch (error) {
        console.error('Generate error:', error);
        if (error.response?.data?.message) {
            ElMessage.error(error.response.data.message);
        } else {
            ElMessage.error('生成失败');
        }
    } finally {
        generating.value = false;
    }
};

// 下载图片
const handleDownload = () => {
    if (!generatedImage.value) return;
    const link = document.createElement('a');
    link.href = generatedImage.value;
    link.download = `workflow-${workflow.value?.id}-${Date.now()}.png`;
    link.click();
};

// 点赞
const handleLike = async () => {
    try {
        const workflowId = workflow.value?.id;
        if (!workflowId) {
            console.error('Invalid workflow ID for like operation');
            ElMessage.error('操作失败');
            return;
        }

        console.log('Liking workflow:', workflowId);
        await workflowApi.likeWorkflow(workflowId);
        liked.value = !liked.value;

        if (workflow.value?.stats) {
            workflow.value.stats.likes += liked.value ? 1 : -1;
        }
    } catch (error) {
        console.error('Like error:', error);
        if (error.response?.data?.message) {
            ElMessage.error(error.response.data.message);
        } else {
            ElMessage.error('操作失败');
        }
    }
};

// 加载历史记录项
const loadHistoryItem = (item: { image: string; params: Record<string, any> }) => {
    generatedImage.value = item.image;
    params.value = { ...item.params };
};

// 下载历史记录图片
const downloadHistoryItem = (item: { image: string }) => {
    const link = document.createElement('a');
    link.href = item.image;
    link.download = `workflow-${workflow.value?.id}-${Date.now()}.png`;
    link.click();
};

// 清空历史
const clearHistory = () => {
    generationHistory.value = [];
};

// 重置参数
const resetParams = () => {
    params.value = {};
};

// 格式化时间
const formatTime = (time: string) => {
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
};

// 编辑工作流
const handleEdit = () => {
    router.push(`/workflow/${workflow.value?.id}/edit`);
};

// 初始化
onMounted(async () => {
    if (!props.id) {
        console.error('No workflow ID provided');
        ElMessage.error('无效的工作流');
        router.push('/workflow');
        return;
    }

    await fetchWorkflow();
    if (!workflow.value?.id) {
        console.error('Failed to load workflow');
        router.push('/workflow');
        return;
    }

    canEdit.value = route.query.from === 'edit' || workflow.value?.author === 'current_user';
});
</script>

<style lang="scss" scoped>
.workflow-preview {
    padding: 20px;

    &__header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 20px;

        .info {
            h2 {
                margin: 0 0 10px;
            }

            .description {
                margin: 0 0 10px;
                color: #666;
            }

            .meta {
                display: flex;
                align-items: center;
                gap: 10px;

                .tag {
                    margin-right: 5px;
                }

                .category {
                    color: #666;
                }
            }
        }

        .actions {
            display: flex;
            gap: 10px;
        }
    }

    .main-content {
        margin-bottom: 20px;
    }

    .preview-card {
        margin-bottom: 20px;

        .preview-container {
            height: 400px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f5f7fa;

            .el-image {
                max-height: 100%;
            }

            .empty-preview {
                text-align: center;
                color: #909399;

                .el-icon {
                    font-size: 48px;
                    margin-bottom: 10px;
                }
            }
        }
    }

    .params-card {
        .params-form {
            max-height: 400px;
            overflow-y: auto;
        }
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .history-card {
        margin-top: 20px;

        .history-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .history-item {
            display: flex;
            align-items: center;
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #ebeef5;

            &:hover {
                background-color: #f5f7fa;
            }

            .el-image {
                width: 80px;
                height: 80px;
                margin-right: 10px;
            }

            .history-item-info {
                flex: 1;
                display: flex;
                justify-content: space-between;
                align-items: center;

                .time {
                    color: #909399;
                    font-size: 12px;
                }
            }
        }
    }

    :deep(.el-icon.active) {
        color: #409eff;
    }
}
</style> 